<!doctype html>
<html>
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-sclae=1.0,user-scalable=0">
	<title>XuLuo</title>
	<script type="text/javascript" src="js/zepto.min.js"></script>
	<style>
		*{ margin:0; padding:0; list-style:none;}
		.box {width:100%;position: relative;display: table;}
		.box ul {margin: 10px auto;width:90%;}
		.box ul li {float:left;height:80px;width:50%;padding: 5px;box-sizing: border-box;}
		.box .item {border-radius:6px;height: 100%;width: 100%;}
	</style>
</head>
<body>
	<div class="box">
	    <ul>
	      <li><div class="item" style="background: orange"></div></li>
	      <li><div class="item" style="background: red"></div></li>
	      <li><div class="item" style="background: gray"></div></li>
	      <li><div class="item" style="background: green"></div></li>
	    </ul>
	</div>
	<script type="text/javascript">
		$.fn.moveSort=function(){
			var startX,endX,startY,endY,currItem,idx;
			var arrY=[],arrX=[],pos=[];
				li=$(this).find('li');
			li.each(function(i){
				$(this).css({
					left:$(this).offset().left,
					top:$(this).offset().top,
					width:$(this).width()
				});
				pos[i]={left:$(this).offset().left,top:$(this).offset().top};
				this.index=i;
			});
			li.each(function(){
				$(this).css({
					position:'absolute'
				});
			});
			li.on('touchstart',function(e){
				e.preventDefault();
				currItem=this;
				startX=e.touches[0].clientX;
				startY=e.touches[0].clientY;
				$(document).on('touchmove',function(e){
					endX=e.touches[0].clientX;
					endY=e.touches[0].clientY;
					idx=currItem.index;
					$(currItem).css({
						'opacity':'0.5',
						'z-index':'999',
						'left':endX-startX+pos[idx].left,
						'top':endY-startY+pos[idx].top
					});
				});
				$(document).on('touchend',function(e){
					$(document).off('touchmove');
					$(document).off('touchend');
					$(currItem).siblings().each(function(i){
						arrX[i]=Math.abs($(currItem).offset().left-$(this).offset().left);
						arrY[i]=Math.abs($(currItem).offset().top-$(this).offset().top);
					});
					var minV=Math.min.apply(null,arrX)+Math.min.apply(null,arrY);
					$(currItem).siblings().each(function(){
						if(
							minV==Math.abs($(currItem).offset().left-$(this).offset().left)+Math.abs($(currItem).offset().top-$(this).offset().top)
						){
							var temp=this.index;
							this.index=currItem.index;
							currItem.index=temp;
							$(this).anim(pos[this.index]);
							$(currItem).anim(pos[currItem.index]);
						}else{
							$(currItem).anim(pos[currItem.index]);
						}
					});
					$(currItem).css({
						"opacity" : "1",
						"z-index" : 0
					});
				});
				return false;
			});
		};
		$('.box').moveSort();
	</script>
</body>
</html>